from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field
from starlette.responses import JSONResponse

from utils.response import ResponseUtil, ResponseModel
from service.commonService import CommonService
from service.sysMonitorService import SysMonitorService
from typing import Optional

router = APIRouter(prefix="", tags=["公共接口"])
common_service = CommonService()


class CaptchaResponseModel(ResponseModel):
    uuid: str = Field(..., description="验证码对应ID")
    img: str = Field(..., description="验证码图片base64")


class LoginData(BaseModel):
    username: str
    password: str
    code: str
    uuid: str


@router.get(
    "/captchaImage",
    response_model=ResponseModel,
    summary="获取登录验证码图片",
    description="获取登录验证码图片",
    response_description="返回验证码图片"
)
async def get_img():
    # 生成验证码
    code = CommonService.generate_code()
    # 生成图片
    img_base64 = CommonService.generate_captcha_image(code)
    # 保存验证码
    uuid_key = CommonService.save_captcha(code)

    return JSONResponse(
        content={
            "code": 200,
            "msg": "验证码生成成功",
            "img": img_base64,
            "uuid": uuid_key
        }
    )


@router.post(
    "/login",
    response_model=ResponseModel,
    summary="后台用户登录",
    description="后台用户登录",
    response_description="返回用户信息和token"
)
async def login(login_data: LoginData, request: Request):
    result = await common_service.login(
        login_data.username,
        login_data.password,
        login_data.code,
        login_data.uuid,
        request
    )
    return JSONResponse(content=result)


@router.post(
    "/logout",
    response_model=ResponseModel,
    summary="用户登出",
    description="清除用户登录状态",
    response_description="返回登出结果"
)
async def logout(request: Request):
    try:
        # 将token加入黑名单
        token = request.state.token
        if await common_service.logout_token(token, request):
            return JSONResponse(
                content={
                    "code": 200,
                    "msg": "登出成功"
                }
            )
        else:
            return JSONResponse(
                content={
                    "code": 201,
                    "msg": "登出失败"
                }
            )
    except Exception as e:
        return JSONResponse(
            content={
                "code": 201,
                "msg": f"系统异常：{str(e)}"
            }
        )


@router.get(
    "/sysMonitor/server",
    response_model=ResponseModel,
    summary="获取服务监控信息",
    description="获取服务监控信息",
    response_description="返回服务监控信息"
)
async def get_server_info():
    """获取服务监控信息"""
    result = SysMonitorService.get_server_info()
    return ResponseUtil.success(data=result)
